<template>
  <div class="container">
    <div class="main">
      <!-- 整个注册盒子 -->
      <div class="loginbox">
        <!-- 左侧的注册盒子 -->
        <div class="loginbox-in">
          <div class="userbox">
            <span class="iconfont">&#xe817;</span>
            <input
              class="user"
              id="user"
              v-model="name"
              placeholder="用户名/邮箱"
            />
          </div>
          <br />
          <div class="pwdbox">
            <span class="iconfont">&#xe775;</span>
            <input
              class="pwd"
              id="password"
              type="password"
              v-model="pwd"
              placeholder="密码"
            />
          </div>
          <br />
          <div class="log-box">
            <div class="form-check form-check-inline">
              <input
                class="form-check-input"
                type="radio"
                name="userType"
                id="normalUser"
                value="normalUser"
                v-model="userType"
              />
              <label class="form-check-label" for="normalUser">普通用户</label>
            </div>
            <div class="form-check form-check-inline">
              <input
                class="form-check-input"
                type="radio"
                name="userType"
                id="admin"
                value="admin"
                v-model="userType"
              />
              <label class="form-check-label" for="admin">管理员</label>
            </div>
          </div>
          <br />
          <div class="log-box">
            <div class="log-box-text">忘记密码</div>
            <button type="primary" class="login_btn" @click="submitForm">
              登录
            </button>
          </div>
          <br />
          <div class="warn">wq♡zw</div>
          <button type="primary" class="register_btn" @click="register">
            若无账号,请点击注册
          </button>
        </div>
        <!-- 右侧的注册盒子 -->
        <div class="background">
          <div>
            <h5 class="bt">登&nbsp;录</h5>
          </div>
          <div class="title">欢迎登录网盘管理系统</div>
        </div>
      </div>
    </div>
  </div>
  <!-- Notification 组件的占位符，你可以根据库或组件的文档来放置它 -->
  <Notification
    :message="notificationMessage"
    :type="notificationType"
    v-if="showNotification"
  />
</template>
<script>
import axios from "axios";
import Notification from "@/components/NotificationComponent.vue";
export default {
  name: "LoginView",
  components: {
    Notification,
  },
  data() {
    return {
      name: "", // 用户名/邮箱
      pwd: "", // 密码
      accountType: null, // 账号类型，可以是'name'或'email'，但通常在后端确定
      error: null, // 存储后端返回的报错信息
      userType: "",
      notificationMessage: "",
      notificationType: "",
      showNotification: false,
      isFadingOut: false,
    };
  },
  computed: {
    // 尝试判断输入的是否是邮箱（注意：这只是一个简单的示例，并不完美）
    isEmail() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return emailRegex.test(this.name);
    },
  },
  methods: {
    async submitForm() {
      // 在这里，我们假设如果isEmail为true，则认为是邮箱，否则认为是用户名
      let accountType = this.isEmail ? "email" : "name";

      // 准备发送的数据
      const formData = {
        accountType,
        account: this.name,
        password: this.pwd,
        userType: this.userType,
      };

      try {
        // 发送POST请求到后端API
        // eslint-disable-next-line no-unused-vars
        const response = await axios.post("/api/login", formData, {
          headers: {
            "Content-Type": "application/json",
            // 注意：如果你的 formData 是 FormData 对象，则不需要设置 'Content-Type' 为 'application/json'
          },
        });
        // 处理后端返回的数据
        console.log("服务器返回的数据：", response.data);
        sessionStorage.setItem("auth_token", response.data.token);
        // 保存用户信息到sessionStorage,当我退出登录后又重新登录时可以直接把账号密码填进去
        // sessionStorage.setItem("user", JSON.stringify(response.data.user));
        this.$store.commit("setLogin", response.data.user); // 提交mutation更新用户信息和登录状态
        // 如果登录成功，处理响应数据...
        this.notificationMessage = "登录成功";
        this.notificationType = "success";
        this.showNotification = true;

        // 等待一段时间后隐藏通知（如果需要）
        setTimeout(() => {
          this.showNotification = false;
          // 通常，你应该将用户重定向到他们之前尝试访问的页面，或者主页
          this.$router.push("/networkdisk");

          // 重置表单和报错信息（如果需要）
          this.name = "";
          this.pwd = "";
          this.error = null;
        }, 1000); // 1秒后隐藏通知
      } catch (error) {
        // 捕获并处理错误，比如显示报错信息
        console.error("登录失败:", error);
        if (
          error.response &&
          error.response.data &&
          error.response.data.errors
        ) {
          // 假设后端返回了具体的验证错误信息
          this.notificationMessage =
            "登录失败: " + error.response.data.errors.account;
        } else {
          this.notificationMessage = "登录时发生错误";
        }
        this.notificationType = "error";
        this.showNotification = true;
      }
    },
    async register() {
      this.$router.push("/register");
    },
    handleNotificationClose() {
      this.showNotification = false;
    },
  },
};
</script>

<style scoped>
.loginbox {
  display: flex;
  position: absolute;
  width: 800px;
  height: 400px;
  top: 49%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 #4e655d;
}

.loginbox-in {
  background-color: #89ab9e;
  width: 240px;
}

.userbox {
  margin-top: 85px;
  height: 30px;
  width: 230px;
  display: flex;
  margin-left: 25px;
}

.pwdbox {
  height: 30px;
  width: 225px;
  display: flex;
  margin-left: 25px;
}

.background {
  width: 570px;
  background-image: url("@/assets/img/login_register/bj.png");
  background-size: cover;
  font-family: sans-serif;
}

.bt {
  padding-top: 15px;
  padding-left: 15px;
  font-size: 20px;
  color: #4e655d;
  width: 80px;
}

.title {
  margin-top: 280px;
  font-weight: bold;
  letter-spacing: 4px;
  font-size: 21px;
  color: #4e655d;
}

.title:hover {
  font-size: 25px;
  transition: all 0.4s ease-in-out;
  cursor: pointer;
}

.uesr-text {
  position: left;
}

input {
  outline-style: none;
  border: 0;
  border-bottom: 1px solid #e9e9e9;
  background-color: transparent;
  height: 20px;
  font-family: sans-serif;
  font-size: 15px;
  color: #445b53;
  font-weight: bold;
}

input::-webkit-input-placeholder {
  font-size: 16px;
  color: #e9e9e9;
}

input:focus {
  border-bottom: 2px solid #445b53;
  background-color: transparent;
  transition: all 0.2s ease-in;
  font-family: sans-serif;
  font-size: 15px;
  color: #445b53;
  font-weight: bold;
}

input:hover {
  border-bottom: 2px solid #445b53;
  background-color: transparent;
  transition: all 0.2s ease-in;
  font-family: sans-serif;
  font-size: 15px;
  color: #000000;
  font-weight: bold;
}

input:-webkit-autofill {
  /* 修改默认背景框的颜色 */
  box-shadow: 0 0 0px 1000px #89ab9e inset !important;
  /* 修改默认字体的颜色 */
  -webkit-text-fill-color: #ffffff;
}

input:-webkit-autofill::first-line {
  /* 修改默认字体的大小 */
  font-size: 15px;
  /* 修改默认字体的样式 */
  font-weight: bold;
}

.log-box {
  font-size: 12px;
  display: flex;
  justify-content: space-between;
  width: 190px;
  margin-left: 30px;
  color: #4e655d;
  margin-top: -5px;
  align-items: center;
}

.log-box-text {
  color: #4e655d;
  font-size: 13px;
  text-decoration: underline;
}

.login_btn {
  background-color: #5f8276;
  /* Green */
  border: none;
  color: #fafafa;
  padding: 5px 22px;
  text-align: center;
  text-decoration: none;
  font-size: 14px;
  border-radius: 20px;
  outline: none;
}

.login_btn:hover {
  box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
    0 17px 50px 0 rgba(0, 0, 0, 0.19);
  cursor: pointer;
  background-color: #0b5137;
  transition: all 0.2s ease-in;
}

.warn {
  margin-top: 10px;
  /* margin-right:120px; */
  margin-left: -120px;
  margin-bottom: 5px;
  font-weight: bold;
  font-size: 17px;
}

.register_btn {
  background-color: transparent;
  /* Green */
  border: none;
  text-decoration: none;
  font-size: 14px;
  /* border-radius: 20px;   */
  color: #4e655d;
  font-size: 12px;
  text-decoration: underline;
  display: flex;
  margin-left: 25px;
  outline: none;
}

.register_btn:hover {
  font-weight: bold;
  cursor: pointer;
}

@font-face {
  font-family: "iconfont";
  src: url("~@/assets/font/login_register/iconfont.eot");
  src: url("~@/assets/font/login_register/iconfont.eot?#iefix")
      format("embedded-opentype"),
    /* IE6-IE8 */ url("~@/assets/font/login_register/iconfont.woff2")
      format("woff2"),
    url("~@/assets/font/login_register/iconfont.woff") format("woff"),
    url("~@/assets/font/login_register/iconfont.ttf") format("truetype"),
    /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
      url("~@/assets/font/login_register/iconfont.svg#iconfont") format("svg");
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 20px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  height: 22px;
  color: #4e655d;
  margin-right: 10px;
  margin-top: 3px;
}

.icon-key:before {
  content: "\e775";
}

.icon-account:before {
  content: "\e817";
}
</style>
